<template>
  <div>
    <group gutter="0">
      <div :id='model.key' v-if="model.key!=10000">
        <x-icon type="ios-pricetags-outline" class="icon-red" v-if="!isClicked&&model.value" @click="toggle"></x-icon>
        <x-icon type="ios-pricetag-outline" class="icon-red" v-if="isClicked&&model.value" @click="toggle"></x-icon>
        <span :style="{verticalAlign:'5px'}" @click="changeText(model.key)" >{{model.value}}</span>
        <span :style="{marginLeft:'40%'}" @click="removeChild(model.key)" v-if='model.key !="0"&&!editing&&model.value'>
          <x-icon type="minus-round" ></x-icon>
          <span :style="{verticalAlign:'5px'}">删除</span>
        </span>
        <x-switch :title="''" v-if='model.key =="0"' v-model="value2" style="display:inline-block;margin-left:50%;"></x-switch>
      </div>
        <draggable v-if="isClicked" class='treeMargin'  v-model="model.lists" :options="{group:'people'}">
         <div v-for="(item,index) in model.lists" :key='item.key' >
          <x-icon type="ios-list-outline" class="icon-red" ></x-icon>
          <span :style="{verticalAlign:'5px'}">
            {{item.value}}
          </span>
         </div>
          <div class='changeTree' @click="addCard(model.key)" slot="footer" v-if="!isFolder&&!editing">
            <x-icon type="plus-round" ></x-icon>
            <span :style="{verticalAlign:'5px'}" >添加名片</span>
          </div>
        </draggable>
    </group>
      <draggable  class='treeMargin' v-show="open" v-if="isFolder" v-model="model.children" :options="{group:'people'}">
      <item v-for="model in model.children" :model="model" :key='model.key'>
      </item>
      </draggable >

  </div>
</template>
<script type="application/ecmascript">
import * as types from '@/vuex/types'
import draggable from 'vuedraggable'
import {CellBox,XSwitch,Group } from 'vux'
import { mapState, mapActions } from 'vuex'
let id = 1000
let fromData = ''
let toData = ''
let fromParentModelChildren = ''  // from 节点的父组件的model
let nodeClicked = undefined   // Attention: 递归的所有组件共享同一个＂顶级作用域＂（这个词或许不太正确，但就这个意思）．即：共享上面这几个let变量．这为实现当前节点的高亮提供了基础．
export default {
    components: {
        draggable,
        CellBox,
        XSwitch,
        Group
    },
    name: 'VueDragTreeCom42',
    data() {
        return {
            value2:true,
            open: false,
            isClicked: false,
            styleObj: {
                background: 'white',
            },
            num:0,
        }
    },

    watch:{
      value2:function(oldVal,newVal){
        this.$store.commit('listView/changeEdit',newVal)
      }
    },
    mounted(){
      this.value2 = this.editing
    },
    props: {
        model: Object,
        'default-text': String, // 填加节点时显示的默认文本．
        'current-highlight': Boolean, // 当前节点高亮
        'hover-color': String,
        'highlight-color': String,
    },
    computed: {
      ...mapState({
        editing:state => state.listView.editing,
        personData:state => state.listView.personData,
        goodsData:state => state.listView.goodsData,
        validaty:state => state.listView.validaty,
      }),
      isFolder() {
          return this.model.children &&
              this.model.children.length
      },
    },
    methods: {
      addCard(vals){
        console.log(vals)
        this.$store.commit(types.HIDEDIALOG,true)
        this.$store.commit(types.GETDIALOGINDEX,vals)
        //console.log(this.validaty)
        return
        console.log(vals)
        let newarr = this.model.lists
        console.log(this.model.lists)
        console.log(newarr.pop())
        return
        if(newarr.pop().key){
          let first  = newarr.pop().key.slice(0,newarr.pop().key.length-1);
          let last   = newarr.pop().key.slice(-1);
           id = parseInt(last)+1
          console.log(first)
          console.log(last)
          console.log(first+id)
          console.log(this.model.lists)
          // this.model.lists.push({
          //   id:id,
          //   name:'新名片123'
          // })
        }else{
          console.log(this.model.lists.length)
          let first = this.model.lists.length+1;
          let id = first+'-1'
          console.log(id)
        }
        console.log()
      },
        changeText(val){//更改标题
          //console.log(this.isClicked)
          if(this.editing){
            return
          }
          const _this = this
          _this.$vux.confirm.prompt('原名称('+_this.model.value+')', {
            title: '更改名称',
            onConfirm (msg) {
             
              _this.value2 = false
              _this.model.value = msg
            }
          })

        },
        toggle() {
            if (this.isFolder) {
                this.open = !this.open
            }
            // 调用vue-drag-tree的父组件中的方法,以传递出当前被点击的节点的id值
            //let rootTree = this.findRoot()
            //　API: 对外开放的当前被点击节点的信息
            //rootTree.$parent.curNodeClicked(this.model, this)

            // 纪录节点被点击的状态
            this.isClicked = !this.isClicked

        },
        exchangeData(rootCom, from, to) {
            //如果drag的目的地是 + - 符号的话，退出。
            if (!to || !from || typeof to == 'string' || from.key == to.key) {
                return
            }

            from = JSON.parse(JSON.stringify(from))
            to = JSON.parse(JSON.stringify(to))
            // copy一个,最后再赋值给state.treeData.这样能保证值的变化都会触发视图刷新(因为JS判断引用类型是否相同是根据内存地址.)
            let treeData = JSON.parse(JSON.stringify(this.model))
            let nodeStack = [treeData]
            let status = 0

            // 如果from或者to节点存在父子/祖辈关系，会报id of undefined的错。这种情况不考虑拖拽功能，所以catch住，返回/return就行
            try {
                // 广度优先遍历,找到涉及数据交换的两个对象.然后交换数据.
                while (!(status === 2)) {
                    let item = nodeStack.shift()
                    if (item.key == from.key) {
                        item.key = to.key
                        item.value = to.value
                        if (to.children && to.children.length > 0) {
                            item['children'] = to.children
                        } else {
                            item.children = []
                        }
                        status++
                        //找到后,跳出当前循环.
                        continue;
                    }
                    if (item.key == to.key) {
                        item.key = from.key
                        item.value = from.value
                        if (from.children && from.children.length > 0) {
                            item['children'] = from.children
                        } else {
                            item.children = []
                        }
                        status++
                        //找到后,跳出当前循环.
                        continue;
                    }
                    if (item.children && item.children.length > 0) {
                        nodeStack = nodeStack.concat(item.children)
                    }
                }
            } catch (e) {
                return
            }
            //API: 对外开放交换后的数据的赋值操作
            rootCom.assignData(treeData)
        },
        changeType() {
            // 用户需要高亮-->才纪录当前被点击节点
            if (this.currentHighlight) {
                nodeClicked = this.model.key
            }
            if (!this.isFolder) {
                this.$set(this.model, 'children', [])
                this.addChild()
                this.open = true
                this.isClicked = true
            }
        },


        addChild() {
          const _this = this
          _this.$vux.confirm.prompt('请填写名称', {
            title: '新增名称',
            onConfirm (msg) {
              console.log(id)
              _this.value2 = false
              _this.model.children.push({
                  name: msg ? msg : 'New Node',
                  id: id++
              })
            }
          })

        },
        removeChild(id) {
            var _this =  this
            _this.$vux.confirm.show({
              title: '删除后不可恢复！确定删除？',
              onConfirm () {
               _this.$store.commit('listView/removeChild',id)
              }
            })   
        },
        dragStart(e) {
            console.log(e)
            // fromData = this.model
            e.dataTransfer.effectAllowed = "move";
            e.dataTransfer.setData("nottext", e.target.innerHTML);
            return true
        },
        dragEnd(e) {
            fromData = undefined
            toData = undefined
            fromParentModelChildren = undefined
        },
        dragOver(e) {
            e.preventDefault()
            return true
        },
        dragOverPlus(e) {
            e.preventDefault()
        },
        dragEnterPlus(e) {
        },
        dragEnter(e) {
            toData = this.model
            let rootTree = this.findRoot()
            rootTree.exchangeData(rootTree.$parent, fromData, toData)
        },
        dragLeave(e) {
            fromData = this.model
            fromParentModelChildren = this.$parent.model.children
            // e.target.style.background = '#7B1FA2'
        },
        drop(e) {
            // toData = this.model
            // e.target.style.background = '#7B1FA2'
        },
        dropPlus(e) {
            // 把from节点插入到当前层级节点的最后一个
            if (this.model.hasOwnProperty('children')) {
                this.model.children.push(fromData)
            } else {
                this.model.children = [fromData]
            }

            // 把from节点从之前的节点删除
            for (let i in fromParentModelChildren) {
                if (fromParentModelChildren[i].key == fromData.key) {
                    fromParentModelChildren.splice(i, 1)
                }
            }
        }
    },
    beforeCreate() {
        this.$options.components.item = require('./DragList.vue').default
    },
    created() {
        // console.log('this.hig', this.highlightColor, '|', this.hoverColor)
    },
}
</script>

<style>
.item {
    cursor: pointer;
}

.bold {
    font-weight: bold;
}

.treeNodeText {
    margin: 2px;
    padding: 0.2rem 0.5rem;
    width: fit-content;
    background: #F9FAFC;
    font-size: 18px;
    color: #324057;
}

.treeMargin {
    margin-left: 2rem;
}

.changeTree {
    width: 100%;
    color: #324057;
}

.vue-drag-node-icon {
    display: inline-block;
    width: 0;
    height: 0;
    padding-right: 3px;
    border-left: 6px solid black;
    border-top: 6px solid transparent;
    border-bottom: 6px solid transparent;
    border-right: 0 solid yellow;
    transition: transform .3s ease-in-out;
}

.nodeClicked {
    transform: rotate(90deg);
}
</style>